﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace ITSM.Filter
{
    public class AuthToken : IActionFilter
    {

        private readonly ITokenHelper _tokenHelper;

        //public AuthToken()
        //{
        //    _tokenHelper = new TokenHelper();
        //}

        public AuthToken(ITokenHelper tokenHelper)
        {
            _tokenHelper = tokenHelper;
        }
        public void OnActionExecuted(ActionExecutedContext context)
        {
            return;
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (context.Controller.GetType().Name == "InspectController")
            {
                if (context.HttpContext.Request.Method == "GET")
                {
                    return;
                }
            }; 
            if(context.RouteData.Values["action"]!=null)
            {
                if (context.RouteData.Values["action"].ToString() == "GetContingencyPlanTableInfoIng")
                {
                    if (context.HttpContext.Request.Method == "GET")
                    {
                        return;
                    }
                };
            }
            if (context.Controller.GetType().Name == "QRLoginController")
            {
                return;
            }
            string token = context.HttpContext.Request.Headers["X-Token"];
            if (string.IsNullOrWhiteSpace(token)||token==null)
            {
                context.Result = new UnauthorizedObjectResult(new { StatusCode = 401 });
                return;
            }
            string[] tokenData = token.Split(";");
            if (tokenData.Length < 2)
            {
                context.Result = new UnauthorizedObjectResult(new { StatusCode = 401 });
                return;
            }
            string userid = tokenData[1];
            token = tokenData[0];
            if (!_tokenHelper.ValiToken(token, null))
            {
                context.Result = new UnauthorizedObjectResult(new { StatusCode = 401 });
                return;
            }
            if (_tokenHelper.ValidateToken(token) != userid)
            {
                context.Result = new UnauthorizedObjectResult(new { StatusCode = 401 });
                return;
            }
        }
    }
}

